package com.jzg.mvc.api.archive;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jzg.common.constant.ArchiveStage;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.Cab;
import com.jzg.common.model.biz.CabStore;
import com.jzg.common.model.sys.SysOrg;
import com.jzg.common.render.Archive;
import com.jzg.common.render.ArchiveWarning;
import com.jzg.common.render.Criminal;
import com.jzg.common.util.CaseUtil;


@Path(value = "/api/archive", viewPath = "")
public class ArchiveController extends BaseController {
	
	protected final static Log log = Log.getLog(CaseUtil.class);

	/**
	 * 年内办件统计
	 */
	public void handleStatistics() {
//		double total=0;
//		double detain=0;//扣留
//		double arrest=0;//逮捕
//		double pending=0;
//		double monitor=0;//监居
//		double prosecution=0;起诉
//		double sentence=0;判决
		String cabinetId=this.getPara("cabinetId");
		Cab cab = Cab.dao.findById(cabinetId);
		if(cab==null) {
			renderError("未找到柜子！");
			return;
		}
		
		Map<String,Integer> map=new HashMap<String, Integer>();
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy");
	        Calendar c = Calendar.getInstance();
	         
	        //过去一年
	        c.setTime(new Date());
	        c.add(Calendar.YEAR, -1);
	        Date y = c.getTime();
	        String year = format.format(y);
	        String policeYear="";
	        
	    	Record record=Db.use("plga").findFirst("SELECT * FROM WebConfig WHERE NId=?",4);
	    	
	    	if(record!=null && !StrKit.isBlank(record.getStr("NResetSApplyArrestNO_M"))) {
	    		policeYear=String.format("%s/%s/%s 00:00:00", year,record.getStr("NResetSApplyArrestNO_M"),record.getStr("NResetSApplyArrestNO_D"));
	    	}else {
	    		policeYear=String.format("%s/%s/%s 00:00:00", year,"12","01");
	    	}
	        
	        System.out.println("=================policeYear|"+policeYear);
	        
			Record office=Db.use("plga").findFirst("SELECT * FROM PoliceOffice WHERE NId=?",cab.getOrgId());
			
			String xinjuSql = "SELECT COUNT(*) from  Stage where NState not in (-1,4) and  (NType=1 or NType = 2 or NType = 3) and DAlarmStart >= '"+policeYear+"'";
			String daibuSql = "SELECT COUNT(*) from  Stage where NState not in (-1,4)  and  NType=8 and DAlarmStart >= '"+policeYear+"'";
			String qubaoSql = "SELECT COUNT(*) from  Stage where NState not in (-1,4)  and  (NType=4 or NType = 5)  and DAlarmStart >= '"+policeYear+"'";
			String jianjuSql = "SELECT COUNT(*) from  Stage where NState not in (-1,4)  and  (NType=6 or NType = 7) and DAlarmStart >= '"+policeYear+"'";
			String qisuSql = "SELECT COUNT(*) from  Stage where NState not in (-1,4)  and  NType=95 and DAlarmStart >= '"+policeYear+"'";
			String panjuSql = "SELECT COUNT(*) from  CaseEval where NState !=-1 and NPassState=3 and  NType=90 and DDoTime >= '"+policeYear+"'";
			
			if(!StrKit.equals("53010302", office.getStr("bmdm")) && !StrKit.equals("53010305", office.getStr("bmdm"))) {
				xinjuSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
				daibuSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
				qubaoSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
				jianjuSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
				qisuSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
				panjuSql += " and  NOfficeId ='"+cab.getOrgId()+"' ";
			}else {
				xinjuSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
				daibuSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
				qubaoSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
				jianjuSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
				qisuSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
				//panjuSql += " and NOfficeId in (select Nid from PoliceOffice  where bmdm!='53010311' ) ";
			}
			
	    	int xinju=Db.use("plga").queryInt(xinjuSql);
	    	int daibu=Db.use("plga").queryInt(daibuSql);
	    	int qubao=Db.use("plga").queryInt(qubaoSql);
	    	int jianju=Db.use("plga").queryInt(jianjuSql);
	    	int qisu=Db.use("plga").queryInt(qisuSql);
	    	int panju=Db.use("plga").queryInt(panjuSql);
	    	
	    	map.put("detain", xinju);//刑拘
	    	map.put("arrest", daibu);//逮捕
	    	map.put("pending", qubao);//取保
	    	map.put("monitor", jianju);
	    	map.put("prosecution", qisu);//起诉
	    	map.put("sentence", panju);//判决
	    	map.put("total", xinju+daibu+qubao+jianju+qisu+panju);
	    	renderSuccess("成功！", map);
		}catch (ActiveRecordException e) {
			renderError("接口异常！");
			log.info(e.getMessage());
			return;
		}
		renderSuccess("成功！", map);
	}
	
	/**
	 * 预警
	 */
	public void warnings() {
		
		String cabinetId = getPara("cabinetId");
		Cab cab = Cab.dao.findById(cabinetId);
		if(cab==null) {
			renderError("未找到柜子！");
			return;
		}
		
		SysOrg org = SysOrg.dao.findById(cab.getOrgId());
		if(org==null) {
			renderError("部门不存在！");
			return;
		}
		
		List<ArchiveWarning> archiveWarnings=new LinkedList<ArchiveWarning>();
		try {
			List<CabStore> stores = CabStore.dao.find("select * from "+CabStore.TABLE_NAME+" where cabId=? and ( status='-1' or status='0' ) ",cabinetId);
			for (CabStore cabStore : stores) {
				
				Record record = null;boolean isofffz = true;
				if(StrKit.equals("53010305", org.getCODE())) {
					isofffz = false;
					record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName,t.SName fzyName, "
									+ " (select top 1 convert(varchar(100),EndTime,102) DAlarmEnd from MCabinet where Case_NO = t.SNO_ order by SendTime desc ) DAlarmEnd "
									+ " from [CASE] t where t.SNO_ = '" + cabStore.getId() + "' ");
				}else {
					record = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName from [CASE] t where t.SNO_ = '"+cabStore.getId()+"' ");
				}
				
				String DAlarmEnd="";String crimeName="";
				if(record!=null) {
					String sqlNormalStr = "select a.SName,a.SIdentityCard,a.NMeasureType,b.DAlarmEnd from Crime a,Stage b where a.NId=b.NCrime "
							+ "	and a.NState <> '-1' and b.NState <> '-1' and ( b.BIsPause is null  or b.BIsPause = '0' ) and a.NCase='"+record.getStr("NId")+"' ";
					List<Record> suspectListList=Db.use("plga").find(sqlNormalStr);
					String endDateStr="";
					for(Record suspect:suspectListList) {
						if(!StrKit.isBlank(endDateStr)) {
							SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
							try {
								Date bt=sdf.parse(suspect.getStr("DAlarmEnd"));
								Date et=sdf.parse(endDateStr);
								if(bt.before(et)) {
									endDateStr = suspect.getStr("DAlarmEnd");
									crimeName = suspect.getStr("SName");
								}
							} catch (ParseException e) {
							}
						}else {
							endDateStr = suspect.getStr("DAlarmEnd");
							crimeName = suspect.getStr("SName");
						}
					}
					
					if(!isofffz && StrKit.notBlank(record.getStr("DAlarmEnd"))) {
						DAlarmEnd = record.getStr("DAlarmEnd");
					}else {
						DAlarmEnd = endDateStr;
					}
				}
				if(!StrKit.isBlank(DAlarmEnd)) {
					ArchiveWarning warning = new ArchiveWarning();
					warning.setId(cabStore.getId());
					warning.setSuspectName(crimeName);
					warning.setArchiveNo(cabStore.getId());
					warning.setExpireDate(DAlarmEnd);
					warning.setCause(record.getStr("STypeName").trim());//record.getStr("SHost")
					warning.setDirector(record.getStr("SHost"));
					archiveWarnings.add(warning);
				}
			}
		} catch (Exception e) {
			renderError("接口异常！");
			log.info(e.getMessage());
			return;
		}
		this.renderSuccess("成功", archiveWarnings);
	}
	
	/**
	 * 案件详情
	 */
	public void getById() {
		
		String cabinetId = getPara("cabinetId");
		Cab cab = Cab.dao.findById(cabinetId);
		if(cab==null) {
			renderError("未找到柜子！");
			return;
		}
		
		String archiveNo = getPara("id");
		Archive archive=new Archive();
		try {
			Record recordCase = Db.use("plga").findFirst("select t.*,(select SName from PoliceOffice where NId=t.NOfficeId ) SName from [CASE] t where t.SNO_ = '"+archiveNo+"' ");
			if(recordCase!=null) {
				archive.setArchiveNo(recordCase.getStr("SNO_"));
				archive.setReason(recordCase.getStr("STypeName").trim());
				
				CabStore cabStore = CabStore.dao.findById(archiveNo);
				archive.setBrief(cabStore==null?"":cabStore.getJyaq());
				archive.setDepartment(recordCase.getStr("SName"));
				archive.setDirectors(recordCase.getStr("SHost"));
			}
			
			List<Criminal> criminals=new LinkedList<Criminal>();
			
			String sqlNormalStr = "select a.SName,a.SIdentityCard,a.NMeasureType,b.DAlarmEnd from Crime a,Stage b where a.NId=b.NCrime "
					+ "	and a.NState <> '-1' and b.NState <> '-1' and b.BisCancle='0' and ( b.BIsPause is null  or b.BIsPause = '0' ) and a.NCase='"+recordCase.getStr("NId")+"' ";
			
			List<Record> suspectListList=Db.use("plga").find(sqlNormalStr);
			for(Record suspect:suspectListList) {
				Criminal criminal=new Criminal();
				criminal.setArchiveNo(archiveNo);
				criminal.setName(suspect.getStr("SName"));
				criminal.setSfzh(suspect.getStr("SIdentityCard"));
				criminal.setStatus(suspect.getStr("NMeasureType"));
				criminal.setStatusName(ArchiveStage.map.get(suspect.getInt("NMeasureType")));
				criminal.setExpireDate(suspect.getStr("DAlarmEnd"));
				criminals.add(criminal);
			}
			archive.setCriminals(criminals);
		} catch (ActiveRecordException e) {
			renderError("接口异常！");
			log.info(e.getMessage());
			return;
		}
		this.renderSuccess("成功!", archive);
	}
	
}

